<template>
  <div class="review-list">
    <div class="container">
      <!-- 页面头部 -->
      <div class="page-header">
        <el-button @click="handleBack" :icon="ArrowLeft" circle />
        <h1>我的评价</h1>
        <div class="placeholder"></div>
      </div>

      <!-- 评价统计 -->
      <el-card class="review-stats-card">
        <div class="review-stats">
          <div class="stat-item">
            <div class="stat-number">{{ reviewStats.totalReviews || 0 }}</div>
            <div class="stat-label">总评价数</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ reviewStats.pendingReviews || 0 }}</div>
            <div class="stat-label">待评价</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ (reviewStats.averageRating || 0).toFixed(1) }}</div>
            <div class="stat-label">平均评分</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ reviewStats.helpfulCount || 0 }}</div>
            <div class="stat-label">有用评价</div>
          </div>
        </div>
      </el-card>

      <!-- 筛选标签 -->
      <el-card class="filter-card">
        <el-tabs v-model="activeTab" @tab-change="handleTabChange">
          <el-tab-pane label="全部评价" name="all" />
          <el-tab-pane label="待评价" name="pending" />
          <el-tab-pane label="已评价" name="completed" />
          <el-tab-pane label="追加评价" name="additional" />
        </el-tabs>
      </el-card>

      <!-- 评价列表 -->
      <div class="reviews-list" v-loading="loading">
        <div v-if="reviews.length === 0 && !loading" class="empty-state">
          <el-empty description="暂无评价记录">
            <el-button type="primary" @click="goToOrders">去看看我的订单</el-button>
          </el-empty>
        </div>

        <div
          v-for="review in reviews"
          :key="review.id"
          class="review-item"
        >
          <!-- 订单信息 -->
          <div class="order-info">
            <el-image
              :src="review.service?.image || '/default-service.jpg'"
              fit="cover"
              class="service-image"
            />
            <div class="service-details">
              <h4>{{ review.service?.name }}</h4>
              <p>{{ review.merchant?.name }}</p>
              <div class="order-meta">
                <span>订单号：{{ review.orderNumber }}</span>
                <span>{{ formatDate(review.serviceDate) }}</span>
              </div>
            </div>
            <div class="order-amount">
              ¥{{ formatAmount(review.orderAmount) }}
            </div>
          </div>

          <!-- 评价状态 -->
          <div class="review-status">
            <el-tag :type="getReviewStatusType(review.status)">
              {{ getReviewStatusText(review.status) }}
            </el-tag>
            <span class="review-time" v-if="review.reviewTime">
              {{ formatDate(review.reviewTime) }}
            </span>
          </div>

          <!-- 已评价内容 -->
          <div v-if="review.status === 'completed'" class="review-content">
            <div class="review-header">
              <el-rate
                :model-value="review.rating"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value} 分"
              />
              <div class="review-actions">
                <el-button
                  v-if="!review.hasAdditional && canAddAdditional(review)"
                  size="small"
                  type="primary"
                  @click="addAdditionalReview(review)"
                >
                  追加评价
                </el-button>
              </div>
            </div>

            <p class="review-text" v-if="review.content">{{ review.content }}</p>

            <!-- 评价图片 -->
            <div class="review-images" v-if="review.images && review.images.length > 0">
              <el-image
                v-for="(image, index) in review.images"
                :key="index"
                :src="image"
                fit="cover"
                class="review-image"
                :preview-src-list="review.images"
                :initial-index="index"
              />
            </div>

            <!-- 商家回复 -->
            <div class="merchant-reply" v-if="review.merchantReply">
              <div class="reply-header">
                <el-icon><ChatDotRound /></el-icon>
                <span>商家回复</span>
              </div>
              <p class="reply-content">{{ review.merchantReply.content }}</p>
              <span class="reply-time">{{ formatDate(review.merchantReply.createdAt) }}</span>
            </div>

            <!-- 追加评价 -->
            <div class="additional-review" v-if="review.additionalReview">
              <div class="additional-header">
                <el-icon><Plus /></el-icon>
                <span>追加评价</span>
                <span class="additional-time">{{ formatDate(review.additionalReview.createdAt) }}</span>
              </div>
              <p class="additional-content">{{ review.additionalReview.content }}</p>
              
              <!-- 追加评价图片 -->
              <div class="additional-images" v-if="review.additionalReview.images?.length > 0">
                <el-image
                  v-for="(image, index) in review.additionalReview.images"
                  :key="index"
                  :src="image"
                  fit="cover"
                  class="review-image"
                  :preview-src-list="review.additionalReview.images"
                  :initial-index="index"
                />
              </div>
            </div>

            <!-- 评价统计 -->
            <div class="review-stats-footer">
              <div class="stats-item">
                <el-icon><View /></el-icon>
                <span>{{ review.viewCount || 0 }} 次查看</span>
              </div>
              <div class="stats-item">
                <el-icon><StarFilled /></el-icon>
                <span>{{ review.helpfulCount || 0 }} 人觉得有用</span>
              </div>
            </div>
          </div>

          <!-- 待评价操作 -->
          <div v-else-if="review.status === 'pending'" class="review-actions">
            <el-button type="primary" @click="writeReview(review)">
              立即评价
            </el-button>
            <span class="deadline-tip" v-if="review.deadline">
              {{ formatDeadline(review.deadline) }}
            </span>
          </div>

          <!-- 过期未评价 -->
          <div v-else-if="review.status === 'expired'" class="expired-notice">
            <el-icon color="#f56c6c"><WarningFilled /></el-icon>
            <span>评价已过期，无法再进行评价</span>
          </div>
        </div>
      </div>

      <!-- 加载更多 -->
      <div class="load-more" v-if="hasMore && !loading">
        <el-button @click="loadMore" :loading="loadingMore">
          加载更多
        </el-button>
      </div>
    </div>

    <!-- 评价弹窗 -->
    <el-dialog
      v-model="showReviewDialog"
      title="评价服务"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="review-form" v-if="currentReview">
        <!-- 服务信息 -->
        <div class="service-info">
          <el-image
            :src="currentReview.service?.image || '/default-service.jpg'"
            fit="cover"
            class="service-image"
          />
          <div class="service-details">
            <h4>{{ currentReview.service?.name }}</h4>
            <p>{{ currentReview.merchant?.name }}</p>
          </div>
        </div>

        <!-- 评分 -->
        <div class="rating-section">
          <h4>服务评分</h4>
          <el-rate
            v-model="reviewForm.rating"
            :texts="['非常差', '差', '一般', '好', '非常好']"
            show-text
            text-color="#ff9900"
          />
        </div>

        <!-- 评价内容 -->
        <div class="content-section">
          <h4>评价内容</h4>
          <el-input
            v-model="reviewForm.content"
            type="textarea"
            :rows="4"
            placeholder="请详细描述您对本次服务的感受..."
            maxlength="500"
            show-word-limit
          />
        </div>

        <!-- 图片上传 -->
        <div class="images-section">
          <h4>上传图片 <span class="optional">(可选)</span></h4>
          <el-upload
            v-model:file-list="reviewForm.images"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :limit="6"
            accept="image/*"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tips">
            最多上传6张图片，每张不超过5MB
          </div>
        </div>

        <!-- 匿名选项 -->
        <div class="anonymous-section">
          <el-checkbox v-model="reviewForm.anonymous">
            匿名评价
          </el-checkbox>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showReviewDialog = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitReview"
            :loading="submitting"
          >
            提交评价
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft,
  ChatDotRound,
  Plus,
  View,
  StarFilled,
  WarningFilled
} from '@element-plus/icons-vue'
import { orderApi } from '@/services/api'
import dayjs from 'dayjs'

const router = useRouter()

// 数据定义
const loading = ref(true)
const loadingMore = ref(false)
const submitting = ref(false)
const reviews = ref([])
const reviewStats = ref({})
const hasMore = ref(false)
const page = ref(1)
const pageSize = ref(10)
const activeTab = ref('all')
const showReviewDialog = ref(false)
const currentReview = ref(null)

// 评价表单
const reviewForm = reactive({
  rating: 5,
  content: '',
  images: [],
  anonymous: false
})

// 生命周期
onMounted(() => {
  fetchReviews()
  fetchReviewStats()
})

// 方法定义
const fetchReviews = async () => {
  try {
    loading.value = true
    
    const params = {
      page: page.value,
      pageSize: pageSize.value,
      status: activeTab.value === 'all' ? undefined : activeTab.value
    }

    const response = await orderApi.getReviews(params)
    const { data, total } = response.data
    
    if (page.value === 1) {
      reviews.value = data
    } else {
      reviews.value.push(...data)
    }
    
    hasMore.value = reviews.value.length < total
  } catch (error) {
    console.error('获取评价列表失败:', error)
    ElMessage.error('获取评价列表失败')
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

const fetchReviewStats = async () => {
  try {
    const response = await orderApi.getReviewStats()
    reviewStats.value = response.data
  } catch (error) {
    console.error('获取评价统计失败:', error)
  }
}

const handleTabChange = (tab) => {
  activeTab.value = tab
  page.value = 1
  fetchReviews()
}

const loadMore = () => {
  page.value++
  loadingMore.value = true
  fetchReviews()
}

const writeReview = (review) => {
  currentReview.value = review
  resetReviewForm()
  showReviewDialog.value = true
}

const addAdditionalReview = (review) => {
  ElMessageBox.prompt('请输入追加评价内容', '追加评价', {
    confirmButtonText: '提交',
    cancelButtonText: '取消',
    inputType: 'textarea',
    inputPlaceholder: '请详细描述追加的评价内容...'
  }).then(async ({ value }) => {
    if (!value.trim()) {
      ElMessage.warning('请输入评价内容')
      return
    }

    try {
      await orderApi.addAdditionalReview(review.orderId, {
        content: value
      })
      
      ElMessage.success('追加评价成功')
      fetchReviews()
    } catch (error) {
      console.error('追加评价失败:', error)
      ElMessage.error('追加评价失败')
    }
  }).catch(() => {
    // 用户取消
  })
}

const submitReview = async () => {
  if (reviewForm.rating === 0) {
    ElMessage.warning('请选择评分')
    return
  }

  if (!reviewForm.content.trim()) {
    ElMessage.warning('请输入评价内容')
    return
  }

  try {
    submitting.value = true

    const reviewData = {
      orderId: currentReview.value.orderId,
      rating: reviewForm.rating,
      content: reviewForm.content,
      anonymous: reviewForm.anonymous,
      images: reviewForm.images.map(item => item.url).filter(Boolean)
    }

    await orderApi.submitReview(reviewData)
    
    ElMessage.success('评价提交成功')
    showReviewDialog.value = false
    fetchReviews()
    fetchReviewStats()
  } catch (error) {
    console.error('提交评价失败:', error)
    ElMessage.error('提交评价失败')
  } finally {
    submitting.value = false
  }
}

const resetReviewForm = () => {
  reviewForm.rating = 5
  reviewForm.content = ''
  reviewForm.images = []
  reviewForm.anonymous = false
}

const canAddAdditional = (review) => {
  // 评价后7天内可以追加评价
  const reviewTime = dayjs(review.reviewTime)
  const now = dayjs()
  return now.diff(reviewTime, 'day') <= 7
}

const getReviewStatusType = (status) => {
  const typeMap = {
    pending: 'warning',
    completed: 'success',
    expired: 'danger'
  }
  return typeMap[status] || 'info'
}

const getReviewStatusText = (status) => {
  const textMap = {
    pending: '待评价',
    completed: '已评价',
    expired: '已过期'
  }
  return textMap[status] || '未知'
}

const goToOrders = () => {
  router.push('/orders')
}

const handleBack = () => {
  router.back()
}

const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD')
}

const formatAmount = (amount) => {
  return parseFloat(amount || 0).toFixed(2)
}

const formatDeadline = (deadline) => {
  const now = dayjs()
  const deadlineTime = dayjs(deadline)
  const diff = deadlineTime.diff(now, 'hour')
  
  if (diff <= 0) {
    return '评价已过期'
  } else if (diff <= 24) {
    return `${diff}小时后过期`
  } else {
    return `${Math.floor(diff / 24)}天后过期`
  }
}
</script>

<style lang="scss" scoped>
.review-list {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px 0;
}

.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;

  h1 {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    color: #333;
  }

  .placeholder {
    width: 32px;
  }
}

.el-card {
  margin-bottom: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.review-stats-card {
  .review-stats {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;

    .stat-item {
      text-align: center;

      .stat-number {
        font-size: 24px;
        font-weight: 600;
        color: #e6a23c;
        margin-bottom: 4px;
      }

      .stat-label {
        color: #666;
        font-size: 14px;
      }
    }
  }
}

.filter-card {
  :deep(.el-card__body) {
    padding: 0;
  }

  :deep(.el-tabs__header) {
    margin: 0;
    padding: 0 20px;
  }

  :deep(.el-tabs__nav-wrap) {
    padding: 16px 0;
  }
}

.reviews-list {
  .empty-state {
    padding: 60px 20px;
    text-align: center;
  }

  .review-item {
    background: white;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

    .order-info {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-bottom: 16px;
      padding-bottom: 16px;
      border-bottom: 1px solid #f0f0f0;

      .service-image {
        width: 80px;
        height: 80px;
        border-radius: 8px;
        flex-shrink: 0;
      }

      .service-details {
        flex: 1;

        h4 {
          margin: 0 0 4px 0;
          font-size: 16px;
          font-weight: 500;
          color: #333;
        }

        p {
          margin: 0 0 8px 0;
          color: #666;
          font-size: 14px;
        }

        .order-meta {
          display: flex;
          gap: 16px;
          color: #999;
          font-size: 12px;
        }
      }

      .order-amount {
        font-size: 18px;
        font-weight: 600;
        color: #e6a23c;
      }
    }

    .review-status {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      .review-time {
        color: #999;
        font-size: 12px;
      }
    }

    .review-content {
      .review-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;
      }

      .review-text {
        margin: 0 0 12px 0;
        color: #333;
        font-size: 14px;
        line-height: 1.6;
      }

      .review-images {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
        gap: 8px;
        margin-bottom: 16px;

        .review-image {
          width: 80px;
          height: 80px;
          border-radius: 4px;
          cursor: pointer;
        }
      }

      .merchant-reply {
        background: #f8f9fa;
        border-radius: 8px;
        padding: 12px;
        margin-bottom: 16px;

        .reply-header {
          display: flex;
          align-items: center;
          gap: 6px;
          margin-bottom: 8px;
          color: #409eff;
          font-size: 14px;
          font-weight: 500;
        }

        .reply-content {
          margin: 0 0 8px 0;
          color: #333;
          font-size: 14px;
          line-height: 1.5;
        }

        .reply-time {
          color: #999;
          font-size: 12px;
        }
      }

      .additional-review {
        background: #fff9e6;
        border: 1px solid #ffd666;
        border-radius: 8px;
        padding: 12px;
        margin-bottom: 16px;

        .additional-header {
          display: flex;
          align-items: center;
          gap: 6px;
          margin-bottom: 8px;

          span:first-of-type {
            color: #e6a23c;
            font-size: 14px;
            font-weight: 500;
          }

          .additional-time {
            margin-left: auto;
            color: #999;
            font-size: 12px;
          }
        }

        .additional-content {
          margin: 0 0 8px 0;
          color: #333;
          font-size: 14px;
          line-height: 1.5;
        }

        .additional-images {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(60px, 1fr));
          gap: 6px;

          .review-image {
            width: 60px;
            height: 60px;
            border-radius: 4px;
          }
        }
      }

      .review-stats-footer {
        display: flex;
        gap: 16px;
        padding-top: 12px;
        border-top: 1px solid #f0f0f0;

        .stats-item {
          display: flex;
          align-items: center;
          gap: 4px;
          color: #999;
          font-size: 12px;
        }
      }
    }

    .review-actions {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .deadline-tip {
        color: #f56c6c;
        font-size: 12px;
      }
    }

    .expired-notice {
      display: flex;
      align-items: center;
      gap: 8px;
      color: #f56c6c;
      font-size: 14px;
    }
  }
}

.load-more {
  text-align: center;
  margin-top: 20px;
}

.review-form {
  .service-info {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #e4e7ed;

    .service-image {
      width: 60px;
      height: 60px;
      border-radius: 8px;
      flex-shrink: 0;
    }

    .service-details {
      h4 {
        margin: 0 0 4px 0;
        font-size: 16px;
        color: #333;
      }

      p {
        margin: 0;
        color: #666;
        font-size: 14px;
      }
    }
  }

  .rating-section,
  .content-section,
  .images-section,
  .anonymous-section {
    margin-bottom: 24px;

    h4 {
      margin: 0 0 12px 0;
      font-size: 14px;
      color: #333;

      .optional {
        color: #999;
        font-weight: normal;
      }
    }
  }

  .upload-tips {
    margin-top: 8px;
    color: #999;
    font-size: 12px;
  }
}

@media (max-width: 768px) {
  .container {
    padding: 0 10px;
  }

  .review-stats {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;

    .stat-item {
      .stat-number {
        font-size: 20px;
      }
    }
  }

  .order-info {
    flex-direction: column;
    align-items: flex-start;

    .service-image {
      align-self: center;
    }

    .order-amount {
      align-self: flex-end;
    }
  }

  .review-images {
    grid-template-columns: repeat(3, 1fr);

    .review-image {
      width: 100%;
      height: 80px;
    }
  }
}
</style> 